import { ElMessage } from 'element-plus';
import NProgress from 'nprogress';
import router from './router';
import store from './store';
import 'nprogress/nprogress.css';
import { getToken, setToken } from '@/utils/auth';
import { isHttp } from '@/utils/validate';

const USE_PERMISSION = true; // 是否使用权限控制
if (!USE_PERMISSION) {
  store.commit('SET_ROUTES', []);
  store.commit('SET_SIDEBAR_ROUTERS', []);
} else {
  NProgress.configure({ showSpinner: false });

  const whiteList = ['/login', '/auth-redirect', '/bind', '/register'];

  router.beforeEach((to, from, next) => {
    // console.log('to', to)
    // console.log('from', from)

    // 实现单点登录
    const token = to.query.token;
    if (token) {
      setToken({
        accessToken: token,
        refreshToken: '',
      });
      // 将query中的token移除
      delete to.query.token;
    }

    NProgress.start();
    if (getToken()) {
      /* has token */
      if (to.path === '/login') {
        next({ path: '/' });
        NProgress.done();
      } else {
        if (store.getters.roles.length === 0) {
          // 判断当前用户是否已拉取完user_info信息
          store
            .dispatch('GetInfo')
            .then((res) => {
              // 拉取user_info
              const roles = res.roles;
              store.dispatch('GenerateRoutes', { roles }).then((accessRoutes) => {
                // console.log(roles,accessRoutes)
                // 根据roles权限生成可访问的路由表
                console.log(accessRoutes);
                accessRoutes.forEach((route) => router.addRoute(route));
                // 根据roles权限生成可访问的路由表
                // accessRoutes.forEach((route) => {
                //   if (!isHttp(route.path) && route.path !== '*') {
                //     router.addRoute(route) // 动态添加可访问路由表
                //   } else if (route.path === '*') {
                //     let otherPath = { path: '/:pathMatch(.*)*', redirect: '/404', hidden: true }
                //     router.addRoute(otherPath) // 动态添加
                //   }
                // })
                // console.log(accessRoutes)
                // router.addRoute(accessRoutes) // 动态添加可访问路由表
                next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
              });
            })
            .catch((err) => {
              store.dispatch('LogOut').then(() => {
                // console.log("test")
                ElMessage.error(err);
                next({ path: '/' });
              });
            });
        } else {
          next();
        }
      }
    } else {
      // 没有token
      if (whiteList.includes(to.path)) {
        // 在免登录白名单，直接进入
        next();
      } else {
        next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
